//
//  JZHNoProductViewController.m
//  极致荟
//
//  Created by hetao on 14-9-10.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHNoProductViewController.h"
#import "JZHReview.h"
#import "OtherUsers.h"
#import "JZHHuiFuTableViewCell.h"
#import "JZHShare.h"
#import "JZHHouViewController.h"
#import "JZHPersonaldetailsViewController.h"
#import "JZHHowLookMeViewController.h"
@interface JZHNoProductViewController ()
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet UIScrollView *scorll;
@property (weak, nonatomic) IBOutlet UIButton *userListbut;
@property (weak, nonatomic) IBOutlet UIView *userheadImageView;
@property (weak, nonatomic) IBOutlet UILabel *titletext;
@property (weak, nonatomic) IBOutlet UILabel *zlable;
@property (weak, nonatomic) IBOutlet UIImageView *topimage;

@end

@implementation JZHNoProductViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initcom:(JZHCommodity *)com
{
    JZHNoProductViewController *jzh=[[JZHNoProductViewController alloc] init];
    jzh.commodity=com;
    return jzh;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"详情";
    //设置左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 12, 20)];
    [leftButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    if(OSVersionIsAtLeastiOS7>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    UIButton *rightButton=[[UIButton alloc] init];
    [rightButton setFrame:CGRectMake(0, 0, 50, 10)];
    [rightButton setTitle:@"提交" forState:UIControlStateNormal];
    [rightButton setTitleColor:TEXTBULE forState:UIControlStateNormal];
    [rightButton setFont:[UIFont systemFontOfSize:18]];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
   //XX self.navigationItem.rightBarButtonItem = rightBarButton;
 
    [self loadSPHttpData];
}
- (void)backAction:(UIButton *)sender
{
    if([UINavigationController miancerr]==1)
    {
        [UINavigationController Pop:self];
    }else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)loadSPHttpData
{
    [MMProgressHUD showWithStatus:@"数据加载中..."];
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:self.commodity.comid],@"contentId", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"topic/topicContentView") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==HTTPReturnCodeSuccess)
        {
            
            NSLog(@"%@",data);
            NSDictionary *datadic=[data objectForKey:@"data"];
            //取出评论数据
            
            NSMutableArray *muarr=[[NSMutableArray alloc]init];
            for(NSDictionary *comdic in [ [data objectForKey:@"data"]objectForKey:@"commentData"])
            {
                JZHReview *rev=[[JZHReview alloc]init];
                OtherUsers *ouser=[[OtherUsers alloc]init];
                
                ouser.userId=[[comdic objectForKey:@"userID"] intValue];
                ouser.username=[comdic objectForKey:@"userName"];
                ouser.userHeadImage=[[datadic objectForKey:@"imgPrefix"] stringByAppendingString:[comdic objectForKey:@"userAvatar"]];
                rev.recUser=ouser;
                rev.comment=[comdic objectForKey:@"content"];
                rev.revdate=[NSDate dateWithTimeIntervalSince1970:[[comdic objectForKey:@"addTime"] longLongValue]];
                [muarr addObject:rev];
                
            }
            self.commodity.rev=muarr;
            [self.table reloadData];
            
            //添加来访者头像
            NSArray *userarr=[[data objectForKey:@"data"] objectForKey:@"footmarkData"];
            [self adduserheadimage:userarr heandpath:[datadic objectForKey:@"imgPrefix"]];
            
            //添加视图内容
            NSDictionary *viewdic=[[data objectForKey:@"data"] objectForKey:@"viewData"];
            self.commodity.comid=[[viewdic objectForKey:@"id"] intValue];
            self.titletext.text=[viewdic objectForKey:@"title"];
            self.zlable.text=[viewdic objectForKey:@"brandName"];
            [ImageCache imageUrl:[[datadic objectForKey:@"imgPrefix"] stringByAppendingString:[viewdic objectForKey:@"coverImg"]] UiImageview:self.topimage];
            [self.topimage.layer setMasksToBounds:YES];
            
            NSArray *textarr=[viewdic objectForKey:@"content"];
            NSArray *imagearr=[viewdic objectForKey:@"image"];
            for(int i=0;i<textarr.count;i++)
            {
                NSDictionary *zdic;
                if(i<imagearr.count)
                {
                    NSString *pathimage=[[datadic objectForKey:@"imgPrefix"] stringByAppendingPathComponent:imagearr[i]];
                    zdic=[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",i+1],@"number",pathimage,@"image", textarr[i],@"content",nil];
                    [self addContentViewimage:YES datadic:zdic];
                }else
                {
                    zdic=[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",i+1],@"number", textarr[i],@"content",nil];
                    [self addContentViewimage:NO datadic:zdic];
                }
            }
            
            [MMProgressHUD dismiss];
            
            ///向服务器发送来访者
            NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:[User defuceUser].userId],@"userId", [NSNumber numberWithInt:self.commodity.comid],@"footmarkId",@"topic_content",@"footmarkType", nil];
            [HttpRequest httpRequestPost:JZHHTTPURL(@"footmark/addfootmark") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
                
                if(rerurncode==0)
                {
                    NSLog(@"来访者添加成功");
                }else if(rerurncode==-4){
                    NSLog(@"来访者添已添加过");
                }else
                {
                    NSLog(@"来访者添已失败");
                }
                
            }];
            
            
        }else
        {
            [MMProgressHUD dismissWithError:@"加载失败！"];
        }
        
    }];
    
}
///添加来访人头像
- (void)adduserheadimage:(NSArray *)arr heandpath:(NSString *)head
{
    if(arr.count<1)
    {
        self.userListbut.hidden=YES;
       
        return;
    }
    self.userListbut.hidden=NO;
    
    for(int i=0;i<arr.count;i++)
    {
        UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(i*35+i*3, 0, 35, 35)];
        image.userInteractionEnabled=YES;
        image.tag=200+[[[arr objectAtIndex:i] objectForKey:@"userID"] intValue];
        [image addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clikchead:)]];
        NSString *path=[head stringByAppendingString:[[arr objectAtIndex:i] objectForKey:@"userAvatar"]];
        [ImageCache imageUrl:path UiImageview:image];
        [self.userheadImageView addSubview:image];
        if(i>6)
        {
            return;
        }
    }
}

- (IBAction)userliset:(id)sender
{
           [self.navigationController pushViewController:[[JZHHowLookMeViewController alloc] initType:3 activit:self.commodity] animated:YES];
  
    
}

- (void)clikchead:(UITapGestureRecognizer *)tap
{
    OtherUsers *user=[[OtherUsers alloc] init];
    user.userId=tap.view.tag-200;
    [self.navigationController pushViewController:[JZHPersonaldetailsViewController shareName:user] animated:YES];
}
//添加内容的分段视图
- (void)addContentViewimage:(BOOL)isshow datadic:(NSDictionary *)dic
{
    CGRect rect=self.table.frame;
    UIView *aview=[[UIView alloc] initWithFrame:CGRectMake(10, rect.origin.y, 300, 100)];
    
    //添加分段的图片
    UIImageView *image=[[UIImageView alloc] init];
    if(isshow)
    {
        [image setFrame:CGRectMake(0, 0, 300, 200)];
        [ImageCache imageUrl:[dic objectForKey:@"image"] UiImageview:image];
    }else
    {
        [image setFrame:CGRectMake(0, 0, 0, 0)];
        image.hidden=YES;
    }
    [aview addSubview:image];
    
    //添加分段数字
    UILabel *numberlable=[[UILabel alloc] initWithFrame:CGRectMake(5, image.frame.origin.y+5+image.frame.size.height, 15, 20)];
    numberlable.text=[dic objectForKey:@"number"];
    [numberlable setFont:[UIFont  fontWithName:@"Helvetica-Bold" size:24 ]];
    [numberlable setTextColor:[UIColor grayColor]];
    [aview addSubview:numberlable];
    
    //添加分段文字内容
    UILabel *contelable=[[UILabel alloc] initWithFrame:CGRectMake(numberlable.frame.origin.x+numberlable.frame.size.width, image.frame.origin.y+10+image.frame.size.height, 270, 30)];
    contelable.numberOfLines=0;
    
    [contelable setFont:[UIFont systemFontOfSize:12]];
    contelable.text=[dic objectForKey:@"content"];
    [contelable sizeToFit];
    [aview addSubview:contelable];
    
    //重新设置主分段视图高度
    [aview setFrame:CGRectMake(aview.frame.origin.x, aview.frame.origin.y, aview.frame.size.width, contelable.frame.size.height+contelable.frame.origin.y+10)];
    [aview.layer setCornerRadius:3];
    [aview.layer setBorderWidth:0.5];
    [aview.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [aview.layer setMasksToBounds:YES];
    [self.scorll addSubview:aview];
    //改变评论列表的坐标
    [self.table setFrame:CGRectMake(rect.origin.x, aview.frame.origin.y+aview.frame.size.height+ 5, rect.size.width, rect.size.height)];
    //设置滚动范围
    if([self.table numberOfRowsInSection:0]==0)
    {
         [self.scorll setContentSize:CGSizeMake (0, self.table.frame.origin.y+10)];
        self.table.hidden=YES;
    }else
    {
         [self.scorll setContentSize:CGSizeMake (0, self.table.frame.origin.y+self.table.frame.size.height)];
        self.table.hidden=NO;
    }
   
    
}
- (IBAction)shoucang:(id)sender
{
    NSString *footType=@"";
    int footid;
   
        footType=@"topic_content";
        footid=self.commodity.comid;

    
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:[User defuceUser].userId],@"userId", [NSNumber numberWithInt:footid],@"favoriteId",footType,@"favoriteType", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"favorite/addFavorite") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        [MMProgressHUD showWithStatus:@"收藏中..."];
        if(rerurncode==0)
        {
            [MMProgressHUD dismissWithSuccess:@"收藏成功"];
        }else if(rerurncode==-4){
            [MMProgressHUD dismissWithError:@"你已经收藏了" afterDelay:1.0];
        }else
        {
            [MMProgressHUD dismissWithError:@"收藏失败"];
        }
        
    }];
}
- (IBAction)puspin:(id)sender
{
    [self.navigationController pushViewController:[[JZHHouViewController alloc]initId:self.commodity type:0] animated:YES];
}
- (IBAction)share:(id)sender
{
    JZHShare *share=[[NSBundle mainBundle]loadNibNamed:@"JZHShare" owner:self options:nil][0];
    [share shareData:@"asdf" shareTxt:@"adf" image:nil];
    [share show:1 viewcontroller:self];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.commodity.rev.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *pengyoucell=@"PengyouCell";
    
    JZHHuiFuTableViewCell *cell=[tableView dequeueReusableHeaderFooterViewWithIdentifier:pengyoucell];
    if(!cell)
    {
        cell=[[NSBundle mainBundle]loadNibNamed:@"JZHHuiFuTableViewCell" owner:self options:nil][0];
    }
    [cell addCellData:self.commodity.rev[indexPath.row] viewconteroller:self isHuiFu:NO];
    
    
    return cell;
}
@end
